import * as React from 'react';
import { Button, SwipeAction, Toast } from 'antd-mobile-v2';
import { Props, State } from '../type';
import styles from './index.module.less';
import AddModal from './component/add-modal';
import DetailModal from './component/detail-modal';
import _ from 'lodash';
import { GenerateUUID, GenerateUUID32 } from '@/utils';
import { moneyCapitalize } from '@/utils/utils';
import { DelReport } from '@/services/laber-declare';
import excelImg from '@/assets/plugins/excel.png';
import { stopBodyScroll, recoverBodyScroll } from '@/utils/index';
import { SecondConfirm } from '@/components/second-confirm';
import { PrintNum, MathRound } from '@/utils';
import history from '@/utils/history';
import { applyType } from '@/constants';
import { APPROVAL_STATUS } from '@/pages/declare/constants';
import { DocDetail } from '@/services/official-doc';
import { DOC_TYPE } from '@/pages/official-doc/components/log/index';
import { getSearchName } from '@/utils';
export class RelatedMattersTable extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  preValue: undefined;
  provideItems: any;
  preProvideItems: any;
  myAddRef: React.RefObject<any>;

  constructor(props: Props) {
    super(props);
    this.preValue = undefined;
    this.preProvideItems = undefined;
    this.state = {
      detailInfo: props?.customProps?.detailInfo || {},
      mattersList: [],
      showAddModal: false,
      showDetailModal: false,
      ids: [],
      values: [],
      editId: undefined,
      editIndex: undefined,
      uuid: GenerateUUID32(),
      showImportResult: {}, // 导入的明细
      delReport: false // 是否删除导入的明细
    };

    this.myAddRef = React.createRef();
  }

  public componentDidMount() {
    console.log('componentDidMount!!!');
    const {
      props: { renderMode }
    } = this;
    const isEmitMode = this.isResubmit();

    if (renderMode === 'detail' || isEmitMode) {
      this.initDetailData();
    }
    if (this.props.form) {
      this.handleUpdateValues();
    } else {
      this.handleUpdateValuesDetail();
    }
  }

  public componentDidUpdate(prevProps: any) {
    const currentValue = this.props.form?.getFieldValue(this.props.code);
    if (
      !_.isEqual(
        prevProps.formValues?.[this.props.code || ''],
        this.props.formValues?.[this.props.code || '']
      ) ||
      !_.isEqual(this.preValue, currentValue)
    ) {
      this.preValue = currentValue;
      if (this.props.form) {
        if (
          !_.isEqual(
            JSON.stringify(this.state.values),
            JSON.stringify(
              this.props.form?.getFieldValue(this.props.code) || [{}]
            )
          ) &&
          _.isArray(this.props.form?.getFieldValue(this.props.code))
        ) {
          this.handleUpdateValues();
        }
      } else {
        this.handleUpdateValuesDetail();
      }
    }
  }

  // 详情数据回显
  initDetailData = () => {
    try {
      const { detailInfo } = this.state;
      const taskCondition = JSON.parse(detailInfo?.taskCondition || '{}');
      let relatedMattersAddList = [];
      if (taskCondition?.relatedMattersAddList) {
        relatedMattersAddList = taskCondition?.relatedMattersAddList || [];
      } else {
        relatedMattersAddList =
          detailInfo?.processListRes?.formData?.relatedMattersAddList || [];
      }

      // 详情的字段relatedMattersAddList?.value?
      if (this.props?.formValues?.relatedMattersAddList?.length) {
        relatedMattersAddList =
          this.props?.formValues?.relatedMattersAddList || [];
      }
      if (this.props?.formValues?.relatedMattersAddList?.value) {
        relatedMattersAddList =
          this.props?.formValues?.relatedMattersAddList?.value || [];
      }

      let provideItemAddList = [];
      if (detailInfo?.extText) {
        const provideItemAddListStr =
          JSON.parse(detailInfo?.extText)?.provideItemAddList || [];
        provideItemAddList = JSON.parse(provideItemAddListStr);
      }

      this.setState({
        mattersList: relatedMattersAddList
      });
      setTimeout(() => {
        this.props.form.setFieldsValue({
          relatedMattersAddList: {
            value: relatedMattersAddList
          }
        });
        if (provideItemAddList.length) {
          this.props.form.setFieldsValue({
            provideItemAddList: {
              ...provideItemAddList
            }
          });
        }
      }, 100);

      const matterId = relatedMattersAddList.reduce(
        (prev: any, item: any, index: number) => {
          const id =
            index === relatedMattersAddList.length - 1
              ? item.id
              : item.id + ',';
          return prev + id;
        },
        ''
      );

      this.props.GaeaOnPropsCallback({
        provideItemAddList: {
          mattersList: relatedMattersAddList,
          matterId
        }
      });
    } catch (e) {
      console.log(e);
    }
  };

  componentWillUnmount() {
    recoverBodyScroll();
  }

  // 通过路由信息获取是否在修改草稿/重新提交 页面
  isResubmit = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('resubmit?') > -1;
    return isEmitMode;
  };

  // 通过路由信息获取是否在详情 页面
  isDetail = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('/declare/detail?') > -1;
    return isEmitMode;
  };

  handleUpdateValues = () => {
    const values = this.props.form?.getFieldValue(this.props.code);
    if (!_.isArray(values)) return;
    // 给每一项设置唯一的ID
    values.forEach((item: any) => {
      const id = GenerateUUID();
      if (!item.id) {
        item.id = id;
      }
    });
    const ids = values.map((item: any) => item.id);
    this.setState({
      values,
      ids
    });
  };

  handleUpdateValuesDetail = () => {
    const values = this.props.formValues?.[this.props.code || ''] || [{}];
    if (!_.isArray(values)) return;
    values.forEach((item) => {
      const id = GenerateUUID();
      if (!item.id) {
        item.id = id;
      }
    });
    const ids = values.map((item) => item.id);
    this.setState({
      values,
      ids
    });
  };

  setUuid = () => {
    const status = getSearchName('status');
    const dataId = getSearchName('applyId');
    const uid = this.isResubmit() && status == 0 ? dataId : this.props.uuid;
    return uid;
  };

  setTotalAmount = (values) => {
    let totalAmount = 0;
    for (let i = 0; i < values.length; i++) {
      totalAmount += values[i].provideAmount;
    }
    if (this.state.showImportResult.totalProvideAmount) {
      totalAmount += Number(this.state.showImportResult.totalProvideAmount);
    }
    totalAmount = parseFloat(totalAmount.toFixed(2));
    const totalAmountText = moneyCapitalize(String(totalAmount));
    this.props.form?.setFieldsValue({
      totalAmount: totalAmount,
      totalAmountText: totalAmountText
    });
  };

  // 删除明细的二次确认
  ensureLaberDelete = (index: number, id: any) => {
    const params = {
      buttons: [
        {
          text: '删除',
          cb: () => {
            this.onMatterDelete(index, id);
          }
        },
        {
          text: '取消'
        }
      ],
      message: '删除后，发放明细中使用了该事项发放标准的人员也会被删除？'
    };
    SecondConfirm(params);
  };
  delTableListByMatterId(
    list: Array<{ matterId: string; [key: string]: any }>,
    matterId: string
  ) {
    if (list.length) {
      const newList: Array<any> = [];
      list.forEach((item) => {
        if (item.matterId != matterId) {
          newList.push(item);
        }
      });
      return newList;
    }
    return [];
  }

  calculateTotalPrice = (fullTableData: Array<any>) => {
    if (!Array.isArray(fullTableData)) {
      return;
    }
    const {
      props: { form }
    } = this;
    const formTotalPrice = fullTableData.reduce(
      (total: any, currentValue: any) => {
        return total + currentValue.provideAmount;
      },
      0
    );
    const totalAmount = MathRound(PrintNum(Number(formTotalPrice)));
    form?.setFieldsValue({
      totalAmount,
      totalAmountText: moneyCapitalize(Number(totalAmount) + '')
    });
  };
  // 删除事项
  onMatterDelete = (index: number, id: any) => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignores
    const mattersList = [...this.state.mattersList];
    mattersList.splice(index, 1);
    const newList: Array<any> = [];
    const provideItemAddList =
      this.props.form.getFieldValue('provideItemAddList') || [];

    let isAllowCustomStandard = false;

    for (const item of mattersList) {
      if (item.isCustomStandard == 1) {
        isAllowCustomStandard = true;
        break;
      }
    }

    if (
      Array.isArray(provideItemAddList?.list) &&
      provideItemAddList?.list.length
    ) {
      provideItemAddList.list.forEach((item: any) => {
        if (id != item.matterId && (isAllowCustomStandard || item.matterId)) {
          newList.push(item);
        }
      });
    }
    this.props.form &&
      this.props.form?.setFieldsValue({
        provideItemAddList: { ...provideItemAddList, list: newList }
      });
    this.setTotalAmount(newList);
    this.setState(
      {
        mattersList: [...mattersList]
      },
      () => {
        this.onMatterChange();
      }
    );
  };

  // 打开修改弹窗
  onLaberEdit = (index: number, item?: any) => {
    const id = item ? item.value : undefined;
    this.setState({
      showAddModal: true,
      editIndex: index,
      editId: id
    });
  };

  //打开添加事项弹框
  openAddModal = () => {
    const { mattersList } = this.state;
    const { setCheckedList } = this.myAddRef.current;
    this.setState({
      showAddModal: true
    });
    if (Array.isArray(mattersList)) {
      setCheckedList && setCheckedList(mattersList);
    }
    stopBodyScroll();
  };

  // 打开明细分页弹框
  openDetailModal = () => {
    this.setState({
      showDetailModal: true
    });
    stopBodyScroll();
  };

  // 关闭明细分页
  onCloseDetail = () => {
    this.setState({
      showDetailModal: false
    });
    recoverBodyScroll();
  };

  onChange = (e) => {
    //
  };

  public closest(el: any, selector: any) {
    const matchesSelector =
      el.matches ||
      el.webkitMatchesSelector ||
      el.mozMatchesSelector ||
      el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }

  onWrapTouchStart = (e: any) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = this.closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  };

  onMatterChange = () => {
    try {
      const { mattersList } = this.state;
      const { form } = this.props;
      let isAllowCustomStandard = false;
      const matterInfo = mattersList.reduce(
        (prev: any, item: any, index: number) => {
          const id = index === mattersList.length - 1 ? item.id : item.id + ',';
          const matterName =
            index === mattersList.length - 1
              ? item.matterName
              : item.matterName + ',';
          prev.text = (prev?.text || '') + matterName;
          prev.value = (prev?.value || '') + id;
          if (item.isCustomStandard == 1) {
            isAllowCustomStandard = true;
          }
          return prev;
        },
        { value: '', text: '' }
      );
      const firstItem = mattersList[0] || {};
      // todo ? 6-10 先传第一个文稿id
      const documentIdText =
        (firstItem?.orgName || '') + (firstItem?.documentCode || '');

      // 设置group控件的code字段
      form &&
        form.setFieldsValue({
          matterId: JSON.parse(JSON.stringify(matterInfo)),
          relatedMattersAddList: {
            value: mattersList
          },
          documentId: { text: documentIdText, value: firstItem?.documentId }
        });

      // 修改 对应控件的props "provideItemAddList"--->对应的是code
      this.props.GaeaOnPropsCallback &&
        this.props.GaeaOnPropsCallback({
          provideItemAddList: {
            matterId: matterInfo.value
          }
        });

      // 当弹窗消失的时候要更新发放明细的数组
      const newList: Array<any> = [];
      const provideItemAddList =
        this.props.form.getFieldValue('provideItemAddList') || {};
      if (
        Array.isArray(provideItemAddList?.list) &&
        provideItemAddList?.list.length
      ) {
        provideItemAddList.list.forEach((item: any) => {
          if (
            matterInfo?.value.indexOf(item.matterId) > -1 ||
            (isAllowCustomStandard && !item.matterId)
          ) {
            newList.push(item);
          }
        });
      }
      form &&
        form.setFieldsValue({
          provideItemAddList: { ...provideItemAddList, list: newList }
        });
    } catch (e) {
      console.log(e);
    }
  };

  getMattersListFromModal = (mattersList: any) => {
    this.setState(
      {
        mattersList
      },
      () => {
        this.onMatterChange();
      }
    );
  };

  hideAddModal = () => {
    this.setState({
      showAddModal: false
    });
  };

  onOpen = () => {
    console.log('global open');
  };

  onClose = () => {
    console.log('global close');
  };

  rightBtnsDetail = (index: number, id: any) => {
    return [
      {
        text: '删除',
        onPress: () => this.ensureLaberDelete(index, id),
        style: {
          backgroundColor: '#FF3A30',
          color: 'white',
          fontSize: '18px',
          padding: '7px',
          lineHeight: 14
        }
      }
    ];
  };

  goDetail = async (item: any) => {
    // console.log("item----{}", item);
    //getSearchName - isMyApply 不能查看公文详情
    const isMyApply = getSearchName('isMyApply');
    console.log('isMyApply:', isMyApply, this.props.renderMode);
    if (isMyApply === '1' || this.props.renderMode !== 'detail') {
      return false;
    }

    const res = await DocDetail(item.documentId);
    console.log('res-----{}', res?.data);

    const { documentEnterType, status, procRecordId, id } = res?.data || {};
    // documentEnterType: 1-线上公文，2-线下公文;
    if (documentEnterType === 1 && status === APPROVAL_STATUS.Pass) {
      return history.push({
        pathname: `/official-doc/detail/${id}`,
        query: {
          procRecordId: procRecordId,
          applyType: applyType.ONLINE_DOCUMENT_APPLY,
          from: 'declareDetail',
          enterType: DOC_TYPE.MY_RECEIVE
        }
      });
    }
    return history.push({
      pathname: `/official-doc/detail/${id}`,
      query: {
        from: 'declareDetail',
        enterType: DOC_TYPE.MY_RECEIVE
      }
    });
  };

  public render() {
    const { renderMode } = this.props;
    const { mattersList, showAddModal, showDetailModal } = this.state;

    const props = {
      enableSearch: true,
      isDeclare: true,
      useExternal: true,
      externalOption: {
        url: '/api/rucMatter/v1/rucMatter/apply/list',
        placeholder: '事项名称/经办人',
        rows: true,
        searchData: {
          keyWord: '', // 搜索关键字
          lastId: '', // 最后一条数据主键
          pageNum: 1,
          pageSize: 50
        },
        formatVal: {
          text: 'matterName',
          value: 'id',
          descTitle: '事项余额：',
          descValue: 'matterTotalUseAble',
          disabled: 'matterTotalUseAble'
        }
      }
    };

    const LIMIT_NUM = 4;

    return (
      <div
        className={
          styles.labercardWrap +
          ' ' +
          (renderMode === 'detail' ? styles.laberCardDetail : '')
        }
        {...this.props.form?.getFieldProps(this.props.code, {
          trigger: this.onChange
        })}
        {...this.props.form?.getFieldProps('matterId', {
          trigger: this.onChange
        })}
      >
        <div className={styles.cardTile}>
          <span>
            {this.props.name + `(${mattersList && mattersList.length})`}
          </span>
          {mattersList.length > LIMIT_NUM && !this.isDetail() ? (
            <span
              className={styles.delBtn}
              onClick={() => this.openDetailModal()}
            >
              查看全部
            </span>
          ) : null}
        </div>
        <div className={styles.cardContent}>
          {mattersList?.length > 0 &&
            mattersList?.map((item: any, index: number) => {
              if (index > LIMIT_NUM) return null;
              return (
                <div key={index}>
                  <SwipeAction
                    style={{ backgroundColor: 'gray' }}
                    right={this.rightBtnsDetail(index, item.id)}
                    onOpen={() => this.onOpen()}
                    onClose={() => this.onClose()}
                    disabled={this.props.renderMode == 'detail'}
                  >
                    <div className={styles.laberDetailContent}>
                      <div className={styles.title}>
                        <div
                          className={styles.titleLeft}
                          onClick={this.goDetail.bind(this, item)}
                        >
                          {item.matterName}
                        </div>
                      </div>
                      <div className={styles.content}>
                        <div className={styles.titleRight}>
                          {`[${item.orgName}][${item.documentCode}]`}
                        </div>
                      </div>
                    </div>
                  </SwipeAction>
                </div>
              );
            })}
        </div>
        {renderMode !== 'detail' ? (
          <div style={{ background: '#f5f5f5', paddingBottom: '8px' }}>
            <Button onClick={this.openAddModal} className={styles.addBtn}>
              + 添加事项
            </Button>
          </div>
        ) : null}

        <AddModal
          {...props}
          showAddModal={showAddModal}
          hideAddModal={this.hideAddModal}
          getMattersListFromModal={this.getMattersListFromModal}
          ref={this.myAddRef}
          renderMode={this.props.renderMode}
          onChange={this.onChange}
          triScope={this.props.triScope}
        />

        {showDetailModal && (
          <DetailModal
            mattersList={mattersList}
            onMatterDelete={this.ensureLaberDelete}
            renderMode={this.props.renderMode}
            form={this.props.form}
            code={this.props.code}
            actionName={this.props.actionName}
            onCloseModal={() => this.onCloseDetail()}
            value={this.state.mattersList}
            goDetail={this.goDetail.bind(this)}
          />
        )}
      </div>
    );
  }
}
